use crate::model::request::UserLoginReq;
use actix_web::{web, Responder, Result};

use crate::handler::handler::send_response;
use crate::model::user;
use crate::pkg::errno::code::Errno::{ErrPassword, ErrToken, ErrUserNotFound, IsOk};
use crate::pkg::token;
use crate::utils::utils::encrypt;

// 后台登录
pub async fn admin_login(u: web::Json<UserLoginReq>) -> Result<impl Responder> {
    // 第一步：查询用户是否存在
    let res_user = user::get_user_info(&u.username).await;
    match res_user {
        Ok(i) => {
            // 第二步：加密密码
            let auth_pwd = encrypt(&u.password);
            if auth_pwd == i.password {
                // 第三步：创建token
                let token_str = token::sign(token::MyClaims {
                    id: i.id,
                    username: i.username,
                });
                match token_str {
                    Ok(t) => send_response(IsOk, Some(t)).await,
                    Err(e) => send_response(ErrToken, None).await,
                }
            } else {
                send_response(ErrPassword, None).await
            }
        }
        Err(e) => send_response(ErrUserNotFound, None).await,
    }
}
